package com.bjpowernode.seckillservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjpowernode.entity.Goods;
import com.bjpowernode.entity.Orders;
import com.bjpowernode.seckillservice.mapper.OrderMapper;
import com.bjpowernode.seckillservice.service.GoodsService;
import com.bjpowernode.seckillservice.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Resource
    private GoodsService goodsService;

    /**
     * 下订单
     * 参数Orders是从mq中获取
     *
     * 1. 查询商品库存
     * 2.若库存充足，则扣减
     * 3.向订单表添加数据
     *
     */
    @Override
    @Transactional
    public int doOrder(Orders orders) {
        //1. 查询商品库存
        Goods goods = goodsService.getById(orders.getGoodsId());

        //2.若库存充足，则扣减
        if (goods.getStore() <= 0) {
            throw new RuntimeException("库存不足，商品id：" + goods.getId());
        }

        //扣减库存
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();

        //update goods set store=store-1 where id=?
        updateWrapper.setSql("store=store-1");
        updateWrapper.eq("id", goods.getId());
        boolean updateResult = goodsService.update(updateWrapper);

        //3.向订单表添加数据
        boolean saveResult = save(orders);


        return updateResult && saveResult ? 1 : 0;
    }
}
